package cn.aimee.oss;

import android.content.Context;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.DeleteObjectRequest;
import com.alibaba.sdk.android.oss.model.DeleteObjectResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

public class OSSManage {

    private static final String TAG = "OSSManage";
    private OSS oss;

    public OSSManage(Context context) {
        oss = initOSS(context);
    }

    public OSS initOSS(Context context) {
        // 推荐使用OSSAuthCredentialsProvider。token过期可以及时更新。
        OSSCredentialProvider credentialProvider = new OSSAuthCredentialsProvider(Config.STS_SERVER_URL);

        //设置网络参数
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000);//连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000);//socket超时，默认15秒
        conf.setMaxConcurrentRequest(5);//最大并发请求书，默认15秒
        conf.setMaxErrorRetry(2);//失败后最大重试次数，默认2次

        //OSSClient是OSS服务的Android客户端，它为调用者提供了一系列的方法进行操作、管理存储空间（Bucket）和文件（Object）等。
        return new OSSClient(context, Config.OSS_ENDPOINT, credentialProvider);
    }

    /**
     *
     * @param bucketName 存储空间名称
     * @param objectName OSS上传文件名称
     * @param uploadFilePath 本地图片的路径
     */
    public void upload(String bucketName, String objectName, String uploadFilePath) {
        Log.i(TAG, "开始上传图片 : " + objectName);
        //构造上传请求
        PutObjectRequest put = new PutObjectRequest(bucketName, objectName, uploadFilePath);

        //异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.i(TAG, "currentSize : " + currentSize + ", totalSize : " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.i(TAG, "上传图片成功");
                //上传成功
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                Log.i(TAG, "上传图片失败");
                //上传失败
                if (null != clientException) {
                    //本地异常，入网络异常
                    clientException.printStackTrace();
                }
                if (null != serviceException) {
                    //服务异常
                    Log.e(TAG, "ErrorCode:" + serviceException.getErrorCode());
                    Log.e(TAG, "RequestId:" + serviceException.getRequestId());
                    Log.e(TAG, "HostId" + serviceException.getHostId());
                    Log.e(TAG, "RawMessage:" + serviceException.getRawMessage());
                }
            }
        });
//        task.cancel(); //取消任务
//        task.waitUntilFinished();//等待上传完成
    }

    public void deleteFile(String objectName) {
        //创建删除请求
        //填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称
        if (null == objectName || objectName.length() == 0) {
            return;
        }
        DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(Config.BUCKET_NAME, objectName);
        //异步删除
        OSSAsyncTask deleteTask = oss.asyncDeleteObject(deleteObjectRequest, new OSSCompletedCallback<DeleteObjectRequest, DeleteObjectResult>() {
            @Override
            public void onSuccess(DeleteObjectRequest request, DeleteObjectResult result) {
                Log.i(TAG, "删除成功");
            }

            @Override
            public void onFailure(DeleteObjectRequest request, ClientException clientException, ServiceException serviceException) {
                Log.i(TAG, "删除失败");
                // 请求异常。
                if (clientException != null) {
                    // 客户端异常，例如网络异常等。
                    clientException.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务端异常。
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });

    }

}
